import Cookies from 'js-cookie'
import config from '@/config'
import storeLocal from 'storejs'
import { getTreePedigree } from './tools'
export const TOKEN_KEY = 'token'

const { cookieExpires } = config

export const setToken = (token) => {
  Cookies.set(TOKEN_KEY, token, { expires: cookieExpires || 1 })
  if (token === '' || token === undefined) {
    console.log('晴空cookies')
    clearCookies()
  }
}

export const getToken = () => {
  const token = Cookies.get(TOKEN_KEY)
  if (token) return token
  else return false
}
export const clearCookies = () => {
  Cookies.remove('juyou.session.id')
}
export const getBtnPermission = () => {
  const permission = storeLocal.get('hd-btn-permission')
  if (permission) return permission
  else return false
}
export const setBtnPermission = (data) => {
  storeLocal.set('hd-btn-permission', data)
}
/**
 * @param {Array} routeMetched 当前路由metched
 * @returns {Array}
 */
export const getBreadCrumbList = (arr, value, id_key, child_key) => {
  let result = getTreePedigree(arr, value, id_key, child_key)
  if (result.length > 0) {
    setBtnPermission(result[result.length - 1].permission === undefined ? '' : result[result.length - 1].permission)
  }
  return result
}
export const hasChild = (item) => {
  return item.children && item.children.length !== 0
}
/**
 * @param {Array} routers 路由列表数组
 * @description 用于找到路由列表中name为home的对象
 */
export const getHomeRoute = (routers, homeName = 'home') => {
  let i = -1
  let len = routers.length
  let homeRoute = {}
  while (++i < len) {
    let item = routers[i]
    if (item.children && item.children.length) {
      let res = getHomeRoute(item.children, homeName)
      if (res.name) return res
    } else {
      if (item.name === homeName) homeRoute = item
    }
  }
  return homeRoute
}

export const showTitle = (item, vm) => {
  let { title } = item.meta
  if (!title) return
  title = (item.meta && item.meta.title) || item.name
  return title
}

export const phpMenusfilter = (data) => {
  return data
}
export const javaMenusfilter = (data) => {
  return data
}
